using System;
using System.Collections.Generic;
using System.Linq;
using ApiProject.Api.Data;
using ApiProject.Api.Entity;
using ApiProject.Api.PramaModel;
using ApiProject.Api.Repository;
using ApiProject.Api.Uitls;
using ApiProject.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

//商品
namespace ApiProject.Api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class CommodityController : ControllerBase
    {
        private IRepository<CommodityDetails> _commditydetaRepository;
        private IRepository<CommodityClassifications> _commClassdetaRepository;
        private IRepository<Commodities> _commdityRepository;
        private IRepository<CommodityDetailPicture> _commpictureRepository;
        private IRepository<ComSpecifications> _comspeRepository;
        private IRepository<SpecificationChildrens> _spechildRepository;
        private IRepository<Specifications> _speRepository;

        private readonly IWebHostEnvironment _hostingEnvironment;


        public CommodityController(

            IRepository<CommodityDetails> commditydetaRepository,
            IRepository<CommodityClassifications> commClassdetaRepository,
            IRepository<Specifications> speRepository,
            IRepository<Commodities> commdityRepository,
            IRepository<ComSpecifications> comspeRepository,
            IRepository<SpecificationChildrens> spechildRepository,
            IRepository<CommodityDetailPicture> commpictureRepository,
            IWebHostEnvironment hostingEnvironment
        )
        {
            _commditydetaRepository = commditydetaRepository;
            _commdityRepository = commdityRepository;
            _commpictureRepository = commpictureRepository;
            _hostingEnvironment = hostingEnvironment;
            _comspeRepository = comspeRepository;
            _spechildRepository = spechildRepository;
            _commClassdetaRepository = commClassdetaRepository;
            _speRepository=speRepository;
        }

        //添加商品详情SKU
        [HttpPost]
        public dynamic AddCommodity(NewComm model)
        {
            //供应商Id
            var uId = model.UserId;
            //价格
            var price = model.Price;
            //库存
            var sumComm = model.Inventory;
            //参数(选中的子类)名称
            var SpeId = model.SpeChildId;
            //传入的商品名称
            var commdName = model.CommodityName;


            //将传入的字符串转换为数组并查找父级参数Id添加
            string[] a = new string[] { };
            string[] othera=new string[]{};
            List<string> b = a.ToList();
            List<string> otherb=othera.ToList();

            string[] strArray = SpeId.Split(',');

            for (int i = 0; i < strArray.Length; i++)
            {
                var spechild = _spechildRepository.Table.Where(x => x.SpchildrenName == strArray[i] && x.IsDelete == false).FirstOrDefault();
                // var strId = spechild.SpecificationId.ToString();
                var strIda=spechild.SpecificationId;
                var strId=_speRepository.Table.Where(x=>x.Id==strIda && x.IsDelete==false).FirstOrDefault();
                var strname=strId.SpecificationName;
                b.Add(strname);
            }
            a = b.ToArray();
            var str = string.Join(",", a);

            for (int i = 0; i < strArray.Length; i++)
            {
                var spechild = _spechildRepository.Table.Where(x => x.SpchildrenName == strArray[i] && x.IsDelete == false).FirstOrDefault();
                var strId = spechild.SpecificationId.ToString();
              
                otherb.Add(strId);
            }
            othera = otherb.ToArray();
            var str1 = string.Join(",", othera);

            





            var commspunow=_commdityRepository.Table.Where(x=>x.CommodityName==commdName).FirstOrDefault();
            //商品SKU
            var commsku = new CommodityDetails
            {
                CommodityId = commspunow.Id,
                Price = price,
                Inventory = sumComm,
                UserId = uId,
                //参数Id串
                SpecificationId = str1,
                SpecificationIdstring=str,
                SpeChildId = SpeId
            };
            _commditydetaRepository.Insert(commsku);

            return JsonHelper
                     .Serialize(new
                     {
                         Code = 200,
                         Data = commsku,
                         Msg = "添加成功"
                     });



        }
        // 添加商品SPU
        [HttpPost, Route("commspu")]
        public dynamic AddSpu(NewComm model)
        {
            //商品名称
            var commname = model.CommodityName;
            //简介
            var commexplain = model.CommodityExplain;
            //分类Id
            var commclassId = model.CommodityClassificationId;
            //供应商Id
            var uId = model.UserId;

            //是否存在该商品
            var commdone = _commdityRepository.Table.Where(x => x.CommodityName == commname && x.IsDelete == false).FirstOrDefault();
            if (commdone != null)
            {
                return JsonHelper
                        .Serialize(new
                        {
                            Code = 1000,
                            Data = "",
                            Msg = "该商品已存在"
                        });

            }
            else
            {
                //商品SPU
                var commspu = new Commodities
                {
                    CommodityName = commname,
                    CommodityExplain = commexplain,
                    CommodityClassificationId = commclassId,
                    UserId = uId
                };
                _commdityRepository.Insert(commspu);

                var comnowspu = _commdityRepository.Table.Where(x => x.CommodityName == commname).FirstOrDefault();
                var comnowspuId = comnowspu.Id;
                var comclassbyId = _commClassdetaRepository.Table.Where(x => x.Id == commclassId && x.IsDelete == false).FirstOrDefault();
                var commclassName = comclassbyId.ClassificationName;
                return JsonHelper
                       .Serialize(new
                       {
                           Code = 200,
                           Data = new
                           {
                               id = comnowspuId,
                               CommodityName = commname,
                               CommodityExplain = commexplain,
                               CommodityClassificationId = commclassId,
                               classificationName = commclassName,
                           },
                           Msg = "添加成功"
                       });
            }
        }

        //删除商品spu
        [HttpPost, Route("delete/{id}")]
        public dynamic deleteSpu(int id)
        {
            var spu = _commdityRepository.Table.Where(x => x.Id == id && x.IsDelete == false).FirstOrDefault();
            spu.IsDelete = true;
            spu.IsEnable = false;
            spu.UpdateTime = DateTime.Now;

            _commdityRepository.Update(spu);

            var commsku = _commditydetaRepository.Table.Where(x=>x.CommodityId==spu.Id).ToList();
            commsku.ForEach(item =>
            {                
                    item.IsDelete = true;
                    item.IsEnable = false;
                    item.UpdateTime = DateTime.Now;
                    _commditydetaRepository.Update(item);
                
            });

            return JsonHelper
                     .Serialize(new
                     {
                         Code = 200,
                         Data = spu,
                         Msg = "删除成功"
                     });
        }



        //伪删除图片
        [HttpDelete("{id}")]
        public dynamic DeleteSpe(int id)
        {
            var Spe = _commpictureRepository.Table.Where(x => x.Id == id && x.IsDelete == false).FirstOrDefault();

            if (Spe != null)
            {

                Spe.IsDelete = true;
                Spe.IsEnable = false;
                Spe.UpdateTime = DateTime.Now;
                _commpictureRepository.Update(Spe);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = Spe,
                    Msg = "删除成功"
                });

            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = "",
                    Msg = "删除失败"
                });
            }

        }



        //添加图片
        [HttpPost, Route("picture/{id}")]
        public dynamic AddCommPicture(int id)
        {
            if (id == 0)
            {
                return JsonHelper
                        .Serialize(new
                        {
                            Code = 1000,
                            Data = "",
                            Msg = "添加图片失败"
                        });
            }
            else
            {
                var files = HttpContext.Request.Form.Files;
                string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot
                var showfilePath = PicHelper.getFilePath(files, "upload", webRootPath);

                var commPicture = new CommodityDetailPicture
                {
                    CommodityId = id,
                    CommodityPicturePath = showfilePath
                };
                _commpictureRepository.Insert(commPicture);
                return JsonHelper
                        .Serialize(new
                        {
                            Code = 200,
                            Data = commPicture,
                            Msg = "添加图片成功"
                        });
            }


        }

        //添加内容
        [HttpPost, Route("content/{id}")]
        public dynamic AddCommContent(int id, NewCommCont model)
        {
            var content = model.mdContent;
            var commCont = new ComSpecifications
            {
                CommodityDetailId = id,
                ComSpecificationContent = content
            };

            _comspeRepository.Insert(commCont);

            return JsonHelper
                        .Serialize(new
                        {
                            Code = 200,
                            Data = commCont,
                            Msg = "成功添加"
                        });

        }

        //获取图片
        [HttpGet("{id}")]
        public dynamic GetCommPicture(int id)
        {
            if (id == 0)
            {
                return JsonHelper
                        .Serialize(new
                        {
                            Code = 1000,
                            Data = "",
                            Msg = "暂无数据"
                        });
            }
            else
            {
                var allPicture = _commpictureRepository.Table.Where(x => x.CommodityId == id && x.IsDelete == false).ToList();
                return JsonHelper
                        .Serialize(new
                        {
                            Code = 200,
                            Data = allPicture,
                            Msg = "获取成功"
                        });
            }

        }





        //获取商品SPU
        [HttpGet, Route("commspu/{id}")]
        public dynamic GetCommSpu(int id)
        {
            // var spu = _commdityRepository.Table.Where(x => x.UserId == id && x.IsDelete == false).ToList();
            var spu = from comm in _commdityRepository.Table
                      join commclass in _commClassdetaRepository.Table on comm.CommodityClassificationId equals commclass.Id
                      where comm.UserId == id && comm.IsDelete == false
                      select new { Id = comm.Id, CommodityName = comm.CommodityName, CommodityExplain = comm.CommodityExplain, ClassificationName = commclass.ClassificationName, CommodityClassificationId = commclass.Id };
            // spu.ForEach(item=>{
            //     item.CommodityClassificationId
            // });

            if (spu == null)
            {
                return JsonHelper
                       .Serialize(new
                       {
                           Code = 1000,
                           Data = "",
                           Msg = "暂无数据"
                       });
            }
            else
            {
                return JsonHelper
                       .Serialize(new
                       {
                           Code = 200,
                           Data = spu,
                           Msg = "获取成功"
                       });
            }
        }


    }
}
